package com.example.springmysqldemo.controller;

import com.example.springmysqldemo.entity.Book;
import com.example.springmysqldemo.result.Result;
import com.example.springmysqldemo.result.ResultBooks;
import com.example.springmysqldemo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class helloController {
    @Autowired
    BookService bookService;
    @RequestMapping("/index")
    public String index(){
        return "Welcome";
    }

    @RequestMapping("/getallbooks")
    public ResultBooks books(){
        List<Book> bookList = bookService.findall();
        return new ResultBooks(200,"获取数据成功",bookList);
    }

    @RequestMapping("/showuser/{id}")
    public Book book(@PathVariable("id") String id){
        Book one = bookService.findOne(id);
        return one;
    }

    @RequestMapping("/deleteBook/{id}")
    public Result deleteBook(@PathVariable("id") String id){
        String s = bookService.deleteBook(id);
        if (s.equals("0")){
            return new Result(400,"删除用户失败！","" );
        }else{
            return new Result(200,"删除用户成功！","");
        }
    }

    @RequestMapping("/addUser")
    @ResponseBody
    public Result addUser(@RequestBody Book book){
         String username = book.getUsername();
         String ustatus = book.getUstatus();
        String s = bookService.addUser(username, ustatus);
        if (s.equals("0")) {
            return new Result(400,"添加用户失败！","");
        }else{
            return new Result(200,"添加用户成功!","");
        }
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    public Result editUser(@RequestBody Book book){
        String new_username = book.getUsername();
        String new_ustatus = book.getUstatus();
        String id = book.getUserId();
        String s = bookService.updateUser(new_username, new_ustatus, id);
        if (s.equals("0")){
            return new Result(400,"编辑用户失败！","");
        }else{
            return new Result(200,"编辑用户成功！","");
        }
    }
}
